/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormDaftarOrderPenjualan.java
 *
 * Created on Apr 6, 2011, 11:28:41 PM
 */

package com.kifas.sales.ui;

import com.kifas.model.xml.CustomerModel;
import com.kifas.model.xml.PengirimanDetailModel;
import com.kifas.model.xml.PengirimanModel;
import com.kifas.model.xml.PenjualanDetailModel;
import com.kifas.model.xml.PenjualanModel;
import com.kifas.service.MasterService;
import com.kifas.service.PengirimanService;
import java.awt.Component;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.swingbinding.JComboBoxBinding;
import org.jdesktop.swingbinding.SwingBindings;
import com.kifas.service.PenjualanService;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 *
 * @author dhamarsu
 */
public class FormDaftarDeliveryOrder extends javax.swing.JInternalFrame {
    private MasterService masterService = new MasterService();

    private List<CustomerModel> customers;
    private PenjualanModel penjualanModel;
    private List<PenjualanModel> salesList;
    private PenjualanService penjualanService = new PenjualanService();
    private PengirimanService pengirimanService = new PengirimanService();
    private DateFormat df = new SimpleDateFormat("ddMMyyyy");
    private List<PenjualanDetailModel> salesDetailList;
    private List<PengirimanModel> pengirimanModels;
    private List<PengirimanModel> pengirimanGridModels;
    private List<PengirimanDetailModel> pengirimanDetailModels;
    
    /** Creates new form FormDaftarOrderPenjualan */
    public FormDaftarDeliveryOrder() {
        initComponents();

        dtEndDate.setDate(new Date());
        dtStartDate.setDate(new Date());

        customers = masterService.getCustomers();

        BindingGroup bindingGroup = new BindingGroup();
        JComboBoxBinding custBinding =
                SwingBindings.createJComboBoxBinding(
                UpdateStrategy.READ,
                customers,
                cboCustomer);

        cboCustomer.setRenderer(new DefaultListCellRenderer() {
           @Override
           public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
               super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
               if (value instanceof CustomerModel) {
                   CustomerModel mec = (CustomerModel)value;
                   setText(mec.getNama());
               }
               return this;
           }
        });

        bindingGroup.addBinding(custBinding);
        bindingGroup.bind();

        tablePenjualan.setAutoCreateColumnsFromModel(false);
        tablePenjualan.getSelectionModel().addListSelectionListener(new SalesSelectionListener());

        salesList = new ArrayList<PenjualanModel>();
        tablePenjualan.setModel(new PenjualanTableModel(salesList));

        tableDetailSales.setAutoCreateColumnsFromModel(false);
        salesDetailList = new ArrayList<PenjualanDetailModel>();
        tableDetailSales.setModel(new PenjualanDetailTableModel(salesDetailList));

    }

    private class SalesSelectionListener implements ListSelectionListener{

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if(tablePenjualan.getSelectedRow()>=0){
                penjualanModel = salesList.get(tablePenjualan.getSelectedRow());
                pengirimanModels = pengirimanService.getPengirimans(penjualanModel.getIdPenjualan());                

                salesDetailList = new ArrayList<PenjualanDetailModel>(penjualanModel.getPenjualanDetails());
                tableDetailSales.setModel(new PenjualanDetailTableModel(salesDetailList));

                pengirimanGridModels = new ArrayList<PengirimanModel>();
                int y = 0;
                for (PengirimanModel pm : pengirimanModels){
                    Iterator iter = pm.getPengirimanDetails().iterator();
                    while (iter.hasNext()) {
                        PengirimanModel pm1 = new PengirimanModel();
                        pm1.setIdJenisEkspedisi(pm.getIdJenisEkspedisi());
                        pm1.setIdPengiriman(pm.getIdPengiriman());
                        pm1.setIdPenjualan(pm.getIdPenjualan());
                        pm1.setKeterangan(pm.getKeterangan());
                        pm1.setNoPengiriman(pm.getNoPengiriman());
                        pm1.setTanggalDo(pm.getTanggalDo());
                        pm1.setTanggalKirim(pm.getTanggalKirim());
                        pm1.setTanggalTerima(pm.getTanggalTerima());
                        Set<PengirimanDetailModel> setPmd1 = new HashSet<PengirimanDetailModel>();
                        setPmd1.add((PengirimanDetailModel) iter.next());
                        pm1.setPengirimanDetails(setPmd1);
                        pengirimanGridModels.add(pm1);
                    }
                }
            }
        }

    }


    private class PenjualanTableModel extends AbstractTableModel{

        private List<PenjualanModel> salesList;

        public PenjualanTableModel(List<PenjualanModel> salesList) {
            this.salesList = salesList;
        }

        public int getRowCount() {
            return salesList.size();
        }

        public int getColumnCount() {
            return 3;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            PenjualanModel s = salesList.get(rowIndex);
            switch(columnIndex){
                case 0: return s.getNoPenjualan();
                case 1: return s.getCustomer().getNama();
                case 2: return s.getSales().getNama();
                case 3: return new SimpleDateFormat("dd/mm/yyyy").format(s.getTanggal());
                case 4: return new SimpleDateFormat("dd/mm/yyyy").format(s.getTanggalKirim());
                case 5: return new SimpleDateFormat("dd/mm/yyyy").format(s.getTanggalJatuhTempo());
                case 6: return s.getTotal();
                default: return "";
            }
        }
    }


    private class PenjualanDetailTableModel extends AbstractTableModel{
        private List<PenjualanDetailModel> salesDetailList;

        public PenjualanDetailTableModel(List<PenjualanDetailModel> salesDetailList) {
            this.salesDetailList = salesDetailList;
        }

        public int getRowCount() {
            return salesDetailList.size();
        }

        public int getColumnCount() {
            return 3;
        }
        
        public Object getValueAt(int rowIndex, int columnIndex) {
            PenjualanDetailModel s = salesDetailList.get(rowIndex);
            Integer qtyKirim = 0;

            if (columnIndex == 4 || columnIndex == 5){
                for (PengirimanModel pm : pengirimanModels){
                    Iterator iter = pm.getPengirimanDetails().iterator();
                    while (iter.hasNext()) {
                        PengirimanDetailModel pmd = (PengirimanDetailModel) iter.next();
                        if (pmd.getBarang().getIdBarang() == s.getBarang().getIdBarang()){
                            qtyKirim += pmd.getQty();
                        }
                    }
                }
            }
            switch(columnIndex){
                case 0: return s.getBarang().getKdBarang();
                case 1: return s.getBarang().getNamaBarang();
                case 2: return s.getBarang().getSatuan().getSatuan();
                case 3: return s.getQty();
                case 4: return qtyKirim;
                case 5: return s.getQty() - qtyKirim;
                default: return "";
            }
        }
    }

    private class PengirimanTableModel extends AbstractTableModel{

        private List<PengirimanModel> pengirimanGridModels;

        public PengirimanTableModel(List<PengirimanModel> pengirimanGridModels) {
            this.pengirimanGridModels = pengirimanGridModels;
        }

        public int getRowCount() {
            return pengirimanGridModels.size();
        }

        public int getColumnCount() {
            return 3;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            PengirimanModel s = pengirimanGridModels.get(rowIndex);            
            PengirimanDetailModel d = new ArrayList<PengirimanDetailModel>(s.getPengirimanDetails()).get(0);
            switch(columnIndex){
                case 0: return d.getGudang().getNamaGudang();
                case 1: return s.getNoPengiriman();
                case 2: return new SimpleDateFormat("dd/MM/yyyy").format(s.getTanggalDo());
                case 3: return d.getBarang().getKdBarang();
                case 4: return d.getBarang().getNamaBarang();
                case 5: return d.getQty();
                case 6: return s.getKeterangan();
                default: return "";
            }
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btnFilter = new javax.swing.JButton();
        dtStartDate = new com.toedter.calendar.JDateChooser();
        dtEndDate = new com.toedter.calendar.JDateChooser();
        jLabel3 = new javax.swing.JLabel();
        cboCustomer = new javax.swing.JComboBox();
        chkAllCustomer = new javax.swing.JCheckBox();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablePenjualan = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableDetailSales = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Daftar Pengiriman");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Filter"));
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel1.setText("Periode");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText("s/d");
        jLabel2.setName("jLabel2"); // NOI18N

        btnFilter.setText("Filter");
        btnFilter.setName("btnFilter"); // NOI18N
        btnFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFilterActionPerformed(evt);
            }
        });

        dtStartDate.setDateFormatString("dd/MM/yyyy"); // NOI18N
        dtStartDate.setName("dtStartDate"); // NOI18N

        dtEndDate.setDateFormatString("dd/MM/yyyy");
        dtEndDate.setName("dtEndDate"); // NOI18N

        jLabel3.setText("Customer");
        jLabel3.setName("jLabel3"); // NOI18N

        cboCustomer.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "C001 - AGUNG MULIA", "C002 - BUDI ASIH" }));
        cboCustomer.setName("cboCustomer"); // NOI18N

        chkAllCustomer.setText("All Customer");
        chkAllCustomer.setName("chkAllCustomer"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cboCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(chkAllCustomer))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(27, 27, 27)
                        .addComponent(dtStartDate, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dtEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnFilter, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(390, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cboCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(chkAllCustomer))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(dtStartDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(dtEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnFilter)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jPanel3.setName("jPanel3"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tablePenjualan.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "No PO", "Customer", "Sales", "Tanggal", "Tanggal Kirim", "Tanggal Jt Tempo", "Total"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablePenjualan.setName("tablePenjualan"); // NOI18N
        jScrollPane1.setViewportView(tablePenjualan);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 974, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Daftar Penjualan", jPanel3);

        jPanel5.setName("jPanel5"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        tableDetailSales.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null}
            },
            new String [] {
                "Kd Barang", "Nama", "Satuan", "Qty", "Qty Kirim", "Qty Sisa"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableDetailSales.setName("tableDetailSales"); // NOI18N
        jScrollPane2.setViewportView(tableDetailSales);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 974, Short.MAX_VALUE)
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Detail Penjualan", jPanel5);

        jToolBar1.setRollover(true);
        jToolBar1.setName("jToolBar1"); // NOI18N

        jButton1.setText("View Report");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setName("jButton1"); // NOI18N
        jButton1.setPreferredSize(new java.awt.Dimension(100, 50));
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton1);

        jButton2.setText("Export Xls");
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setName("jButton2"); // NOI18N
        jButton2.setPreferredSize(new java.awt.Dimension(100, 50));
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton2);

        jButton3.setText("Print");
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setName("jButton3"); // NOI18N
        jButton3.setPreferredSize(new java.awt.Dimension(100, 50));
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 982, Short.MAX_VALUE)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 982, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(26, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFilterActionPerformed
        // TODO add your handling code here:
        if (chkAllCustomer.isSelected()){
            salesList = penjualanService.getPenjualansByDateStatusSent(df.format(dtStartDate.getDate()),
            df.format(dtEndDate.getDate()), true);
        }else{
            salesList = penjualanService.getPenjualansByDateStatusSent(df.format(dtStartDate.getDate()),
            df.format(dtEndDate.getDate()), true);
        }
        tablePenjualan.setModel(new PenjualanTableModel(salesList));
    }//GEN-LAST:event_btnFilterActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnFilter;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cboCustomer;
    private javax.swing.JCheckBox chkAllCustomer;
    private com.toedter.calendar.JDateChooser dtEndDate;
    private com.toedter.calendar.JDateChooser dtStartDate;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTable tableDetailSales;
    private javax.swing.JTable tablePenjualan;
    // End of variables declaration//GEN-END:variables

}
